import { defineStore } from "pinia";
import type { ILoginData } from "@/services/modules/login/type";
import { getUserInfoById, getUserMenusByRoleId, userLogin } from "@/services/modules/login";
import { localCache } from "@/utils/cache";
import { LOGIN_TOKEN, USER_INFO, USER_MENUS } from "@/constants";
import type { ILoginState } from "@/stores/modules/login/type";
import router from "@/router";
import { mapMenuListToPermission, mapMenus } from "@/utils/mapMenus";
import useSystemStore from "@/stores/modules/main/system/system";

const useLoginStore = defineStore("login", {
  state: (): ILoginState => ({
    userInfo: localCache.getCache(USER_INFO) ?? {},
    token: localCache.getCache(LOGIN_TOKEN) ?? "",
    userMenus: localCache.getCache(USER_MENUS) ?? [],
    permissions: []
  }),
  actions: {
    async userLoginAction(loginData: ILoginData) {
      // 获取用户登录返回信息
      const res = await userLogin(loginData);
      const id = res.data.id;
      // 处理 token
      this.token = res.data.token;
      localCache.setCache(LOGIN_TOKEN, res.data.token);
      // 获取用户信息
      const userInfoResult = await getUserInfoById(id);
      this.userInfo = userInfoResult.data;
      localCache.setCache(USER_INFO, userInfoResult.data);
      // 获取权限
      const userMenusResult = await getUserMenusByRoleId(id);
      this.userMenus = userMenusResult.data;
      localCache.setCache(USER_MENUS, userMenusResult.data);
      // 获取所有 role 和 department 和 menu 数据
      const systemStore = useSystemStore();
      await systemStore.postRoleListAction();
      await systemStore.postDepartmentListAction();
      await systemStore.postMenuListAction();
      // 获取当前用户的按钮权限列表
      this.permissions = mapMenuListToPermission(this.userMenus);
      // 动态添加路由
      const routes = mapMenus(this.userMenus);
      routes.forEach((route) => router.addRoute("main", route));
      // 路由跳转到首页
      router.push("/");
    },

    loadAsyncRoutes() {
      // 用户刷新 动态获取路由 防止因为刷新导致缓存的动态路由丢失
      if (this.token && this.userMenus && this.userInfo) {
        const systemStore = useSystemStore();
        // 获取所有 role 和 department 和 menu 数据
        systemStore.postRoleListAction();
        systemStore.postDepartmentListAction();
        systemStore.postMenuListAction();
        // 获取按钮权限列表
        this.permissions = mapMenuListToPermission(this.userMenus);
        // 动态添加路由
        const routes = mapMenus(this.userMenus);
        routes.forEach((route) => {
          router.addRoute("main", route);
        });
      }
    }
  }
});

export default useLoginStore;
